package io.xmu.dataanalysis.data;

import com.google.common.collect.Maps;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import io.xmu.dataanalysis.entity.Category;
import io.xmu.dataanalysis.entity.Goods;
import io.xmu.dataanalysis.entity.Shop;
import io.xmu.dataanalysis.entity.User;
import io.xmu.dataanalysis.repository.CategoryRepo;
import io.xmu.dataanalysis.repository.GoodsRepo;
import io.xmu.dataanalysis.repository.ShopRepo;
import io.xmu.dataanalysis.repository.UserRepo;

/**
 * @author lepdou 2017-02-27
 */
@Component
public class BaseDataCache {

  private Random random = new Random();

  @Autowired
  private ShopRepo shopRepo;
  @Autowired
  private CategoryRepo categoryRepo;
  @Autowired
  private UserRepo userRepo;
  @Autowired
  private GoodsRepo goodsRepo;


  private List<Shop> shops;
  private List<User> users;
  private List<Goods> goodses;
  private List<Category> cates;

  private Map<Integer, Goods> goodsMap = Maps.newHashMap();
  private Map<Integer, Shop> shopMap = Maps.newHashMap();

  private Map<Integer, Integer> shopIdMapCateId = new HashMap<Integer, Integer>();
  private Map<String, Integer> cateMap = new HashMap<>();

  public void init() {

    users = asList(userRepo.findAll());
    shops = asList(shopRepo.findAll());
    goodses = asList(goodsRepo.findAll());
    cates = asList(categoryRepo.findAll());

    for (Goods goods: goodses) {
      goodsMap.put(goods.getId(), goods);
    }

    for (Shop shop: shops) {
      shopMap.put(shop.getId(), shop);
    }

    for (Category c: cates) {
      cateMap.put(c.getName(), c.getId());
    }
  }

  private <T> List<T> asList(Iterable<T> iterable) {
    List<T> result = new ArrayList<T>();

    if (iterable == null) {
      return result;
    }

    for (T t: iterable) {
      result.add(t);
    }

    return result;

  }

  public User randomUser() {
    return random(users);
  }

  public Shop randomShop() {
    return random(shops);
  }

  public Goods randomGoods() {
    return random(goodses);
  }

  public int getCateIdFromShopId(int shopId) {
    return shopIdMapCateId.get(shopId);
  }

  public Goods getGoods(int goodsId) {
    return goodsMap.get(goodsId);
  }

  public Shop getShop(int shopId) {
    return shopMap.get(shopId);
  }

  public Integer cateId(String cateName) {
    return cateMap.get(cateName);
  }

  private <T> T random(List<T> set) {
    int size = set.size();
    return set.get(random.nextInt(size));
  }

}
